package cxydmmszl.chapter01.t001;

import java.util.Stack;

/**
 * 设计一个有 getMin 功能的栈
 * @author habitplus
 * @since 2021-08-04 20:44
 */
public class MyStack01 {
    private final Stack<Integer> dataStack = new Stack<>();
    private final Stack<Integer> minStack = new Stack<>();


    /**
     * 入栈：每次都将当前最小的数压入 minStack
     */
    public void push(int num) {
        if (dataStack.isEmpty()) {
            minStack.push(num);
        } else {
            int top = minStack.peek();
            if (top > num) minStack.push(num);
            else minStack.push(top);
        }
        dataStack.push(num);
    }

    /**
     * 出栈：dataStack 与 minStack 同时出栈
     */
    public int pop() {
        ensureNonEmpty();
        minStack.pop();
        return dataStack.pop();
    }

    /**
     * getMin 函数
     */
    public int getMin() {
        ensureNonEmpty();
        return minStack.peek();
    }

    private void ensureNonEmpty() {
        if (dataStack.isEmpty())
            throw new RuntimeException("The stack is empty!");
    }

    /**
     * 返回栈顶元素
     */
    public int peek() {
        ensureNonEmpty();
        return dataStack.peek();
    }
}
